package com.ggsoft.webapp.jsf;

/**
 * @date   Jan 6, 2011
 * @author Ggutierrez
 */


import com.ggsoft.timetracker.utils.Persistent;
import com.ggsoft.timetracker.utils.ObjectLookup;
import com.ggsoft.webapp.action.BasePage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.web.jsf.FacesContextUtils;

/**
 *
 * @author lruiz
 */
public class ObjectConverter extends BasePage implements Converter{
    private ObjectLookup objectLookup;


    public ObjectConverter() {
    }

    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String string) {

        Class clazz = getTargetClass(uiComponent, facesContext);
        if (StringUtils.hasText(string)) {            
            return getObjectLookup().find(new Long(string), clazz);
        }
        return null;
    }

    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object object) {
        if (object == null || ((Persistent) object).getId() == null) {
            return "";
        }
        return String.valueOf(((Persistent) object).getId());
    }

    public ObjectLookup getObjectLookup() {
        if (objectLookup == null) {
            ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
            objectLookup = (ObjectLookup) ctx.getBean("objectLookup");
        }
        return objectLookup;
    }

    private Class getTargetClass(UIComponent uiComponent, FacesContext facesContext) {
        return uiComponent.getValueExpression("value").getType(facesContext.getELContext());
    }
}
